using UnityEngine;
using UnityEngine.Events;

public abstract class BasePanel : MonoBehaviour
{
    private CanvasGroup canvasGroup;
    //淡出成功后执行委托函数
    private UnityAction hideCallBack;
    [SerializeField]
    private float alphaSpeed = 10f;
    //当前面板的状态：false为隐藏，true为显示
    private bool nowState;
    protected virtual void Awake()
    {
        canvasGroup = this.GetComponent<CanvasGroup>();
        if (canvasGroup == null)
            canvasGroup = gameObject.AddComponent<CanvasGroup>();
    }
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    protected virtual void Start()
    {
        Init();
    }

    // Update is called once per frame
    void Update()
    {
        //淡入
        if (nowState && canvasGroup.alpha != 1)
        {
            canvasGroup.alpha += alphaSpeed * Time.deltaTime;
            if (canvasGroup.alpha > 1)
                canvasGroup.alpha = 1;
        }
        //淡出
        else if (!nowState && canvasGroup.alpha != 0)
        {
            canvasGroup.alpha -= alphaSpeed * Time.deltaTime;
            if (canvasGroup.alpha < 0)
            {
                canvasGroup.alpha = 0;

            }
            //?的作用是：不为null时才会执行
            hideCallBack?.Invoke();
        }
    }
    /// <summary>
    /// 主要用于初始化按钮事件监听等内容
    /// </summary>
    //抽象类中的抽象方法，子类必须要实现
    public abstract void Init();
    public virtual void ShowMe()
    {
        nowState = true;
        //显示时，初始化透明度为0（也就是完全透明），在update中随时间变为1
        canvasGroup.alpha = 0;
    }
    public virtual void HideMe(UnityAction callBack)
    {
        nowState = false;
        //显示时，初始化透明度为1（也就是完全显示），在update中随时间变为0（透明）
        canvasGroup.alpha = 1;
        //记录传入的委托（当淡入成功后的回调函数）
        hideCallBack = callBack;

    }
}
